package com.example.network;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class HttpEngine {

	public static class KeyValue {

		public String key;

		public String value;

		public KeyValue() {
		}

		public KeyValue(String key, String value) {
			this.key = key;
			this.value = value;
		}

	}

	private static final String tag = "result";

	public static String doPost(String actionurl, String params, String type) {
		Log.v(tag, "address:" + actionurl + "|" + params);
		InputStream is = null;
		HttpURLConnection conn = null;
		String result = null;
		// TODO Auto-generated method stub
		try {
			URL url = new URL(actionurl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod(type);
			conn.setReadTimeout(10 * 1000);
			conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
			conn.connect();
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
			out.write(params);
			out.flush();
			out.close();
			is = conn.getInputStream();
			if (is != null) {
				result = StringUtils.convertStreamToString(is);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return result;
	}

	public static String uploadFile(String URI, List<NameValuePair> parameters, InputStream is, String fname) {
		try {
			String boundary = "*****" + System.currentTimeMillis();
			String twoHyphens = "--";
			String end = "\r\n";
			URL url = new URL(URI);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			if (parameters != null) {
				String name = "";
				String value = "";
				for (int index = 0; index < parameters.size(); index++) {
					name = parameters.get(index).getName();
					value = parameters.get(index).getValue();
					out.writeBytes(twoHyphens + boundary + end);
					out.writeBytes("Content-Disposition:form-data;name=\"" + name + "\"" + end + end);
					out.write(value.getBytes("UTF-8"));
					out.writeBytes(end);
				}
			}
			out.writeBytes(twoHyphens + boundary + end);
			out.writeBytes("Content-Disposition:form-data;name=\"p.image\";filename=\"");
			// out.write(file.getName().getBytes("UTF-8"));
			out.write(fname.getBytes("UTF-8"));
			out.writeBytes("\"" + end);
			out.writeBytes("Content-Type:application/octet-stream" + end + end);
			// FileInputStream in = new FileInputStream(file);
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			while ((length = is.read(buffer)) != -1) {
				out.write(buffer, 0, length);
			}
			out.writeBytes(end);
			out.writeBytes(twoHyphens + boundary + twoHyphens + end);
			out.flush();
			String jsonObject = getResponseStr(connection);
			return jsonObject;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	private static String getResponseStr(HttpURLConnection connection) {
		try {
			int length = -1;
			byte[] buffer = new byte[1024];
			InputStream ins = connection.getInputStream();
			byte[] result = null;
			byte[] temp = null;
			while ((length = ins.read(buffer)) != -1) {
				if (result == null) {
					result = new byte[length];
					for (int i = 0; i < length; i++)
						result[i] = buffer[i];
				} else {
					temp = new byte[result.length + length];
					for (int i = 0; i < result.length; i++)
						temp[i] = result[i];
					for (int i = 0; i < length; i++)
						temp[i + result.length] = buffer[i];
					result = new byte[temp.length];
					for (int i = 0; i < temp.length; i++)
						result[i] = temp[i];
				}
			}
			String jsonObject = new String(result);
			return jsonObject;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String doGet(String address) {
		Log.v(tag, "get:address-->" + address);
		HttpGet request = new HttpGet(address);
		try {
			HttpResponse response = new DefaultHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(response.getEntity());
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String formPost(String url, List<KeyValue> keyValueList, String cookie) {
		String resultString = null;
		HttpPost httpRequest = new HttpPost(url);
		String logUrl = url;
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (int i = 0; i < keyValueList.size(); i++) {
			String key = keyValueList.get(i).key;
			String value = keyValueList.get(i).value;
			params.add(new BasicNameValuePair(key, value));
			Log.v(tag, "key:" + key + "|value:" + value);
			if (i == 0) {
				logUrl = logUrl + "?" + key + "=" + value;
			} else {
				logUrl = logUrl + "&" + key + "=" + value;
			}
		}
		Log.e(tag, logUrl);
		try {
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			if (cookie != null)
				httpRequest.setHeader("Cookie", cookie);
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			int code = httpResponse.getStatusLine().getStatusCode();
			if (code == 200) {
				resultString = EntityUtils.toString(httpResponse.getEntity());
			} else {
				Log.v(tag, "server back errorCode:" + code);
			}
			// Header[] h = httpResponse.getAllHeaders();
			// for( int i = 0 ; i < h.length; i++ ){
			// Log.v( tag , "name:" + h[i].getName() + "   value:" +
			// h[i].getValue() );
			// }
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.e(tag, "service api:" + url + ":back" + resultString);
		return resultString;
	}

	public static String postImg(String filePath) {
		return "";
	}

	public static class BitmapAndCookie {

		public Bitmap bitmap;

		public String cookie;
	}

	public static Bitmap getBitmap(String url) {
		Bitmap bitmap = null;
		URL myFileUrl = null;
		HttpURLConnection conn = null;
		InputStream is = null;
		try {
			try {
				myFileUrl = new URL(url);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			try {
				conn = (HttpURLConnection) myFileUrl.openConnection();
				conn.setDoInput(true);
				conn.connect();
				is = conn.getInputStream();
				bitmap = BitmapFactory.decodeStream(is);
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return bitmap;
	}

	public static BitmapAndCookie getBitMap(String url) {
		BitmapAndCookie bitmap = null;
		URL myFileUrl = null;
		HttpURLConnection conn = null;
		InputStream is = null;
		try {
			try {
				myFileUrl = new URL(url);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			try {
				conn = (HttpURLConnection) myFileUrl.openConnection();
				conn.setDoInput(true);
				conn.connect();
				String cookie = conn.getHeaderField("Set-Cookie");
				bitmap = new BitmapAndCookie();
				is = conn.getInputStream();
				bitmap.cookie = cookie;
				bitmap.bitmap = BitmapFactory.decodeStream(is);
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return bitmap;
	}
}